package com.gitee.hermer.boot.jee.api;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.NoHandlerFoundException;

import com.gitee.hermer.boot.jee.api.domain.BaseInfo;
import com.gitee.hermer.boot.jee.commons.exception.ErrorCode;
import com.gitee.hermer.boot.jee.commons.exception.PaiUException;
import com.gitee.hermer.boot.jee.commons.log.UtilsContext;

public class BaseControllerHandler extends UtilsContext{
	
    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;

    protected String getProtocolVersion()
    {
        return request.getProtocol();
    }
    protected void writeError(Throwable e){ 
    	error(e.getMessage(),e);
    }

   
    @ExceptionHandler(PaiUException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseInfo handleCFException(PaiUException e){
    	writeError(e);
        return new BaseInfo(getProtocolVersion(),e);
    }
   
    @ExceptionHandler(Throwable.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public BaseInfo handleCFException(Throwable e){
    	writeError(e);
        return new BaseInfo(getProtocolVersion(),new PaiUException(ErrorCode.SYSTEM_ERROR,e,e.getMessage()));
    }
    
    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    public BaseInfo handleNotFoundException(HttpServletRequest request,
    		NoHandlerFoundException ex) {
    	writeError(ex);
        PaiUException e = new PaiUException(ErrorCode.PAGE_NO_FIND_ERROR,ex);
        return new BaseInfo(getProtocolVersion(),e);
    }
    
    


}
